package uk.co.richardwkirk.parkrun.web;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class WebConnection {

	public boolean checkURLExists(String eventURL) throws ParkrunWebException {
		try {
			URL url = new URL(eventURL);
			HttpURLConnection con = createConnection(url);
			return (con.getResponseCode() == 200);
		} catch (IOException e) {
			throw new ParkrunWebException("Could not connect to parkrun site:" + eventURL, e);
		}
	}

	private HttpURLConnection createConnection(URL url) throws IOException {
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.addRequestProperty("User-Agent", "Mozilla/4.76");
		return con;
	}

	public InputStreamReader loadStreamReader(String resourceAddress) throws ParkrunWebException {
		try {
			// Open a connection to read the web page
			URL url = new URL(resourceAddress);
			HttpURLConnection con = createConnection(url);
			if (con.getResponseCode() != 200) {
				throw new ParkrunWebException("Parkrun site responded with non-OK HTTP response (200) for page " + resourceAddress + " it gave " + con.getResponseCode());
			}

			// Get an input stream from the connection
			//Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
			//Matcher m = p.matcher(con.getContentType());
			//String charset = m.matches() ? m.group(1) : "ISO-8859-1";
			InputStreamReader r = new InputStreamReader(con.getInputStream(), "UTF-8");
			return r;
		} 
		catch (UnsupportedEncodingException e) {
			throw new ParkrunWebException("Could not read data stream from parkrun website.", e);
		} 
		catch (IOException e) {
			throw new ParkrunWebException("Could not create connection to parkrun website.", e);
		}
	}

}
